// pages/discipline/index.js
Page({
  data: {
    today: '',
    currentTime: '',
    sleepTime: '',
    wakeTime: '',
    isSleepChecked: false,
    isWakeChecked: false,
    sleepRecords: [],
    weeklyStats: {
      sleepOnTime: 0,
      wakeOnTime: 0,
      totalDays: 0
    },
    // 操作频率限制
    operationCount: 0,
    lastOperationTime: 0
  },

  onLoad: function () {
    this.updateTime();
    this.loadTodayRecords();
    this.loadWeeklyStats();
    
    // 每分钟更新一次时间
    setInterval(() => {
      this.updateTime();
      // 每分钟重置操作次数
      this.resetOperationCount();
    }, 60000);
  },

  onShow: function () {
    this.loadTodayRecords();
    this.loadWeeklyStats();
  },

  // 重置操作次数
  resetOperationCount: function () {
    this.setData({
      operationCount: 0
    });
  },

  // 检查操作频率限制
  checkOperationLimit: function () {
    const now = Date.now();
    const timeDiff = now - this.data.lastOperationTime;
    
    // 如果距离上次操作不到1分钟，检查操作次数
    if (timeDiff < 60000) {
      if (this.data.operationCount >= 6) {
        wx.showToast({
          title: '操作过于频繁，请稍后再试',
          icon: 'none',
          duration: 2000
        });
        return false;
      }
    } else {
      // 超过1分钟，重置操作次数
      this.setData({
        operationCount: 0
      });
    }
    
    // 更新操作记录
    this.setData({
      operationCount: this.data.operationCount + 1,
      lastOperationTime: now
    });
    
    return true;
  },

  // 格式化日期为中文
  formatDate: function (date) {
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const weekdays = ['日', '一', '二', '三', '四', '五', '六'];
    const weekday = weekdays[date.getDay()];
    
    return `${year}年${month}月${day}日 星期${weekday}`;
  },

  // 格式化时间为中文
  formatTime: function (date) {
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    
    return `${hours}:${minutes}`;
  },

  // 更新时间
  updateTime: function () {
    const now = new Date();
    const today = this.formatDate(now);
    const currentTime = this.formatTime(now);
    
    this.setData({
      today: today,
      currentTime: currentTime
    });
  },

  // 设置睡眠时间
  setSleepTime: function () {
    const now = new Date();
    const currentTime = this.formatTime(now);
    
    this.setData({
      sleepTime: currentTime
    });
  },

  // 设置起床时间
  setWakeTime: function () {
    const now = new Date();
    const currentTime = this.formatTime(now);
    
    this.setData({
      wakeTime: currentTime
    });
  },

  // 早睡打卡
  checkSleep: function () {
    if (!this.checkOperationLimit()) {
      return;
    }

    const now = new Date();
    const currentHour = now.getHours();
    const currentMinute = now.getMinutes();
    
    // 判断是否早睡（建议22:00前）
    const isEarlySleep = currentHour < 22 || (currentHour === 22 && currentMinute === 0);
    
    const record = {
      date: this.data.today,
      time: this.data.currentTime,
      type: 'sleep',
      isOnTime: isEarlySleep,
      timestamp: Date.now()
    };

    this.saveRecord(record);
    
    this.setData({
      isSleepChecked: true
    });

    wx.showToast({
      title: isEarlySleep ? '早睡打卡成功！' : '打卡成功，建议早点休息',
      icon: 'success',
      duration: 2000
    });
  },

  // 取消早睡打卡
  cancelSleep: function () {
    if (!this.checkOperationLimit()) {
      return;
    }

    // 删除今日的早睡记录
    this.deleteRecord('sleep');
    
    this.setData({
      isSleepChecked: false
    });

    this.loadTodayRecords();
    this.loadWeeklyStats();

    wx.showToast({
      title: '早睡打卡已取消',
      icon: 'success',
      duration: 2000
    });
  },

  // 早起打卡
  checkWake: function () {
    if (!this.checkOperationLimit()) {
      return;
    }

    const now = new Date();
    const currentHour = now.getHours();
    const currentMinute = now.getMinutes();
    
    // 判断是否早起（建议7:00前）
    const isEarlyWake = currentHour < 7 || (currentHour === 7 && currentMinute === 0);
    
    const record = {
      date: this.data.today,
      time: this.data.currentTime,
      type: 'wake',
      isOnTime: isEarlyWake,
      timestamp: Date.now()
    };

    this.saveRecord(record);
    
    this.setData({
      isWakeChecked: true
    });

    wx.showToast({
      title: isEarlyWake ? '早起打卡成功！' : '打卡成功，继续保持！',
      icon: 'success',
      duration: 2000
    });
  },

  // 取消早起打卡
  cancelWake: function () {
    if (!this.checkOperationLimit()) {
      return;
    }

    // 删除今日的早起记录
    this.deleteRecord('wake');
    
    this.setData({
      isWakeChecked: false
    });

    this.loadTodayRecords();
    this.loadWeeklyStats();

    wx.showToast({
      title: '早起打卡已取消',
      icon: 'success',
      duration: 2000
    });
  },

  // 保存记录到云端
  saveRecord: function (record) {
    const app = getApp();
    if (!app.globalData.isLogin) {
      // 未登录时保存到本地
      let records = wx.getStorageSync('sleepRecords') || [];
      records.push(record);
      wx.setStorageSync('sleepRecords', records);
      return;
    }

    // 已登录时保存到云端
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      data: {
        type: 'sleepRecord',
        action: 'add',
        data: record
      }
    }).then(res => {
      if (res.result.success) {
        console.log('记录已保存到云端');
        // 同时保存到本地作为缓存
        let records = wx.getStorageSync('sleepRecords') || [];
        records.push(record);
        wx.setStorageSync('sleepRecords', records);
      } else {
        console.error('云端保存失败:', res.result.message);
        // 云端保存失败时保存到本地
        let records = wx.getStorageSync('sleepRecords') || [];
        records.push(record);
        wx.setStorageSync('sleepRecords', records);
      }
    }).catch(err => {
      console.error('云端调用失败:', err);
      // 云端调用失败时保存到本地
      let records = wx.getStorageSync('sleepRecords') || [];
      records.push(record);
      wx.setStorageSync('sleepRecords', records);
    });
  },

  // 删除记录
  deleteRecord: function (type) {
    const app = getApp();
    if (!app.globalData.isLogin) {
      // 未登录时从本地删除
      let records = wx.getStorageSync('sleepRecords') || [];
      const today = this.formatDate(new Date());
      const updatedRecords = records.filter(record => 
        !(record.date === today && record.type === type)
      );
      wx.setStorageSync('sleepRecords', updatedRecords);
      return;
    }

    // 已登录时从云端删除
    // 这里需要先获取云端记录的ID，暂时只处理本地数据
    let records = wx.getStorageSync('sleepRecords') || [];
    const today = this.formatDate(new Date());
    const updatedRecords = records.filter(record => 
      !(record.date === today && record.type === type)
    );
    wx.setStorageSync('sleepRecords', updatedRecords);
  },

  // 加载今日记录
  loadTodayRecords: function () {
    const app = getApp();
    if (!app.globalData.isLogin) {
      // 未登录时从本地加载
      const records = wx.getStorageSync('sleepRecords') || [];
      const today = this.formatDate(new Date());
      const todayRecords = records.filter(record => record.date === today);
      
      const sleepRecord = todayRecords.find(record => record.type === 'sleep');
      const wakeRecord = todayRecords.find(record => record.type === 'wake');
      
      this.setData({
        sleepRecords: todayRecords,
        isSleepChecked: !!sleepRecord,
        isWakeChecked: !!wakeRecord
      });
      return;
    }

    // 已登录时从云端加载
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      data: {
        type: 'sleepRecord',
        action: 'getToday'
      }
    }).then(res => {
      if (res.result.success) {
        const todayRecords = res.result.data || [];
        const sleepRecord = todayRecords.find(record => record.type === 'sleep');
        const wakeRecord = todayRecords.find(record => record.type === 'wake');
        
        this.setData({
          sleepRecords: todayRecords,
          isSleepChecked: !!sleepRecord,
          isWakeChecked: !!wakeRecord
        });
        
        // 同步到本地缓存
        wx.setStorageSync('sleepRecords', todayRecords);
      }
    }).catch(err => {
      console.error('云端加载失败:', err);
      // 云端加载失败时从本地加载
      const records = wx.getStorageSync('sleepRecords') || [];
      const today = this.formatDate(new Date());
      const todayRecords = records.filter(record => record.date === today);
      
      const sleepRecord = todayRecords.find(record => record.type === 'sleep');
      const wakeRecord = todayRecords.find(record => record.type === 'wake');
      
      this.setData({
        sleepRecords: todayRecords,
        isSleepChecked: !!sleepRecord,
        isWakeChecked: !!wakeRecord
      });
    });
  },

  // 加载周统计
  loadWeeklyStats: function () {
    const app = getApp();
    if (!app.globalData.isLogin) {
      // 未登录时从本地计算
      const records = wx.getStorageSync('sleepRecords') || [];
      const now = new Date();
      const weekStart = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      
      const weeklyRecords = records.filter(record => {
        const recordDate = new Date(record.date);
        return recordDate >= weekStart;
      });
      
      const sleepOnTime = weeklyRecords.filter(record => 
        record.type === 'sleep' && record.isOnTime
      ).length;
      
      const wakeOnTime = weeklyRecords.filter(record => 
        record.type === 'wake' && record.isOnTime
      ).length;
      
      this.setData({
        weeklyStats: {
          sleepOnTime: sleepOnTime,
          wakeOnTime: wakeOnTime,
          totalDays: 7
        }
      });
      return;
    }

    // 已登录时从云端加载
    wx.cloud.callFunction({
      name: 'quickstartFunctions',
      data: {
        type: 'sleepRecord',
        action: 'getWeekly'
      }
    }).then(res => {
      if (res.result.success) {
        const weeklyRecords = res.result.data || [];
        
        const sleepOnTime = weeklyRecords.filter(record => 
          record.type === 'sleep' && record.isOnTime
        ).length;
        
        const wakeOnTime = weeklyRecords.filter(record => 
          record.type === 'wake' && record.isOnTime
        ).length;
        
        this.setData({
          weeklyStats: {
            sleepOnTime: sleepOnTime,
            wakeOnTime: wakeOnTime,
            totalDays: 7
          }
        });
      }
    }).catch(err => {
      console.error('云端统计加载失败:', err);
      // 云端加载失败时从本地计算
      const records = wx.getStorageSync('sleepRecords') || [];
      const now = new Date();
      const weekStart = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
      
      const weeklyRecords = records.filter(record => {
        const recordDate = new Date(record.date);
        return recordDate >= weekStart;
      });
      
      const sleepOnTime = weeklyRecords.filter(record => 
        record.type === 'sleep' && record.isOnTime
      ).length;
      
      const wakeOnTime = weeklyRecords.filter(record => 
        record.type === 'wake' && record.isOnTime
      ).length;
      
      this.setData({
        weeklyStats: {
          sleepOnTime: sleepOnTime,
          wakeOnTime: wakeOnTime,
          totalDays: 7
        }
      });
    });
  },

  // 查看历史记录
  viewHistory: function () {
    wx.navigateTo({
      url: '/pages/discipline/history'
    });
  }
});
